﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.Globalization;
using Microsoft.SharePoint.Administration;
using System.Web;
using System.Net.Mail;
using System.Web.UI;

namespace LifeInSharePoint.Common
{
    public static class Utilities
    {

        public static string ComputeHash(string Input)
        {
            MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
            byte[] InputArray = System.Text.Encoding.ASCII.GetBytes(Input);
            byte[] HashedArray = MD5.ComputeHash(InputArray);
            MD5.Clear();
            return BitConverter.ToString(HashedArray).Replace("-", "");
        }

        public static string TokenReplacement(string input)
        {
            switch (input)
            {
                case "~SiteCollection":
                    input = input.Replace("~SiteCollection", SPContext.Current.Site.Url);
                    break;

                case "~Site":
                    input = input.Replace("~Site", SPContext.Current.Web.Url);
                    break;

            }
            return input;
        }

        public static void LogError(string errorMessageTitle, Exception ex)
        {
            SPDiagnosticsService diagSvc =
            SPDiagnosticsService.Local;
            diagSvc.WriteTrace(0, new SPDiagnosticsCategory("LifeInSharePoint.Common", TraceSeverity.Monitorable, EventSeverity.Error), TraceSeverity.Monitorable, errorMessageTitle + ":  {0}", new object[] { ex.Message });
        }


        public static void SendEmailSharepoint(SPWeb web, string targetAddress, string fromAddress, string subject, string body)
        {
            SPUtility.SendEmail(web, true, false, targetAddress, subject, body);
        }



        public static string RetrieveConfigValue(string category, string filtername, string cacheName)
        {
            try
            {
                SPListItemCollection _workItemCollection;
                SPListItem _workItem;

                if (HttpRuntime.Cache[cacheName] == null)
                {
                    SPWeb _currentWeb = SPContext.Current.Site.RootWeb;
                    SPList workList = _currentWeb.Lists["ConfigList"];
                    SPQuery workQuery = new SPQuery();
                    workQuery.RowLimit = 1;
                    workQuery.Query = "<Where><And><Eq><FieldRef Name='Title' /><Value Type='Text'>" + filtername + "</Value></Eq><Eq><FieldRef Name='ConfigCategory' /><Value Type='Text'>" + category + "</Value></Eq></And></Where>";

                    _workItemCollection = workList.GetItems(workQuery);
                    _workItem = _workItemCollection[0];
                    if (_workItemCollection.Count > 0)
                    {
                        HttpRuntime.Cache.Add(cacheName,
                        _workItem,
                        null,
                        DateTime.MaxValue,
                        TimeSpan.FromMinutes(10),
                        System.Web.Caching.CacheItemPriority.Default, null);
                    }
                }
                else
                {
                    _workItem = (SPListItem)HttpRuntime.Cache[cacheName];
                }


                return _workItem["ConfigValue"].ToString();
            }
            catch
            {
                return string.Empty;
            }
        }

        public static string RetrieveConfigValueFromReceiver(string category, string filtername, string cacheName, SPWeb _currentWeb)
        {
            SPListItemCollection _workItemCollection;
            SPListItem _workItem;

            if (HttpRuntime.Cache[cacheName] == null)
            {
                SPList workList = _currentWeb.Lists["ConfigList"];
                SPQuery workQuery = new SPQuery();
                workQuery.RowLimit = 1;
                workQuery.Query = "<Where><And><Eq><FieldRef Name='Title' /><Value Type='Text'>" + filtername + "</Value></Eq><Eq><FieldRef Name='ConfigCategory' /><Value Type='Text'>" + category + "</Value></Eq></And></Where>";

                _workItemCollection = workList.GetItems(workQuery);
                _workItem = _workItemCollection[0];
                if (_workItemCollection.Count > 0)
                {
                    HttpRuntime.Cache.Add(cacheName,
                    _workItem,
                    null,
                    DateTime.MaxValue,
                    TimeSpan.FromMinutes(10),
                    System.Web.Caching.CacheItemPriority.Default, null);
                }
            }
            else
            {
                _workItem = (SPListItem)HttpRuntime.Cache[cacheName];
            }


            return _workItem["ConfigValue"].ToString();
        }

        public static void SendMailMessage(string from, string to, string bcc, string cc, string replyto, string subject, string body, SmtpClient mSmtpClient)
        {
            // Instantiate a new instance of MailMessage
            MailMessage mMailMessage = new MailMessage();
            // Set the sender address of the mail message
            mMailMessage.From = new MailAddress(from);
            // Set the recepient address of the mail message
            mMailMessage.To.Add(new MailAddress(to));

            // Check if the bcc value is null or an empty string
            if ((bcc != null) && (bcc != string.Empty))
            {
                // Set the Bcc address of the mail message
                mMailMessage.Bcc.Add(new MailAddress(bcc));
            }
            // Check if the cc value is null or an empty value
            if ((cc != null) && (cc != string.Empty))
            {
                // Set the CC address of the mail message
                mMailMessage.CC.Add(new MailAddress(cc));
            }       // Set the subject of the mail message
            mMailMessage.Subject = subject;
            // Set the body of the mail message
            mMailMessage.Body = body;

            if ((replyto != null) && (replyto != string.Empty))
            {
                mMailMessage.ReplyTo = new MailAddress(replyto);
            }
            // Set the format of the mail message body as HTML
            mMailMessage.IsBodyHtml = true;
            // Set the priority of the mail message to normal
            mMailMessage.Priority = MailPriority.Normal;

            // Send the mail message
            mSmtpClient.Send(mMailMessage);

            SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("EMAIL Sending Utility", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, "Email Sent From Utility Function, Time Sent: " + DateTime.Now.ToLongTimeString());
        }

    }
}